package com.woniu.hisgateway.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @version: java version 1.8
 * @Author: Mr Ni
 * @description:
 * @date: 2022-09-21 17:29
 */
public class JwtUtil {

    private static String secrt = "asldkfhaewiufhnskjdhfsahfewqiuksjdhk1234KHDAdsafasfadsa";

    private static Integer defaultTime = 1;


    public static String create(Map<String,Object> maps,Integer time){

        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        JwtBuilder builder = Jwts.builder();
        if(maps!=null&&maps.size()>0) builder.setClaims(maps);
        if (time==null) time = defaultTime;
        builder.setExpiration(new Date(System.currentTimeMillis() + time * 600000));
        builder.signWith(key);
        return builder.compact();
    }


    public static String create(Map<String, Object> maps){

        return create(maps,null);
    }

    public static String create(Integer time){

        return create(null,time);
    }

    public static String create(){

        return create(null,null);
    }

    public static Claims parse(String token){
        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        Claims body = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
        return body;
    }

//    public static Integer getUserId(){
//        Cookie[] cookies = WebUtil.getRequest().getCookies();
//        String token = "";
//        for (Cookie cookie : cookies) {
//            if(cookie.getName().equals("user.token")){
//                token = cookie.getValue();
//            }
//        }
//        try {
//            Claims parse = parse(token);
//            Integer userId = (Integer) parse.get("userId");
//            return userId;
//        }catch (Exception e){
//            throw new UserException("未登录",401);
//        }
//    }

}
